﻿using System;
using System.Data;
using System.Linq;

namespace AugustaDevelopersGuild.Models
{
    public class MeetingRepository : IMeetingRepository
    {
        GuildMeetings db = new GuildMeetings();

        public IQueryable<Meeting> FindUpcoming()
        {
            return from x in All
                   where x.EventDate >= DateTime.Now
                   orderby x.EventDate
                   select x;
        }

        public IQueryable<Meeting> FindByText(string q)
        {
            return All.Where(x => x.Speaker.Contains(q) || x.Topic.Contains(q));
        }

        public void DeleteRsvp(Rsvp rsvp)
        {
            db.Rsvps.Remove(rsvp);
            db.SaveChanges();
        }

        public IQueryable<Meeting> All
        {
            get { return db.Meetings; }
        }

        public Meeting Find(int id)
        {
            return All.SingleOrDefault(x => x.MeetingID == id);
        }

        public void InsertOrUpdate(Meeting item)
        {
            if (item.MeetingID == default(int))
            {
                db.Meetings.Add(item);
            }
            else
            {
                db.Entry(item).State = EntityState.Modified;
            }
        }

        public void Delete(int id)
        {
            var item = Find(id);
            foreach (Rsvp rsvp in item.Rsvps.ToList())
                db.Rsvps.Remove(rsvp);
            db.Meetings.Remove(item);
        }

        public void Save()
        {
            db.SaveChanges();
        }
    }
}